package com.zhijiaoyun.aliyun.oss;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ListBucketsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectAcl;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectRequest;

/**
 * @author shisfish
 * @date 2017/12/12
 */
public class OSSTest {

    private static String key = "test/11.jpg";

    public static void main(String[] args) throws IOException {
        /*
         * Constructs a client instance with your account for accessing OSS
         */
        OSSClient ossClient = new OSSClient(OSSConfig.END_POINT, OSSConfig.ACCESS_KEY_ID, OSSConfig.ACCESS_KEY_SECRET);

        System.out.println("Getting Started with OSS SDK for Java\n");

        try {

            /*
             * Determine whether the bucket exists
             */
            if (!ossClient.doesBucketExist(OSSConfig.BUCKET_NAME)) {
                /*
                 * Create a new OSS bucket
                 */
                System.out.println("Creating bucket " + OSSConfig.BUCKET_NAME + "\n");
                ossClient.createBucket(OSSConfig.BUCKET_NAME);
                CreateBucketRequest createBucketRequest= new CreateBucketRequest(OSSConfig.BUCKET_NAME);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            /*
             * List the buckets in your account
             */
            System.out.println("Listing buckets");

            ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
            listBucketsRequest.setMaxKeys(500);

            for (Bucket bucket : ossClient.listBuckets()) {
                System.out.println(" - " + bucket.getName());
            }
            System.out.println();

            /*
             * Upload an object to your bucket
             */
            System.out.println("Uploading a new object to OSS from a file\n");
//            String callBack = "{\"callbackBody\":\"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var=${x:my_var}\"}";
            PutObjectRequest putObjectRequest = new PutObjectRequest(OSSConfig.BUCKET_NAME, key, createSampleFile());
//            Callback call = new Callback();
//            call.setCallbackBody(callBack);
//            putObjectRequest.setCallback(call);
            ossClient.putObject(putObjectRequest);

            /*
             * Determine whether an object residents in your bucket
             */
            boolean exists = ossClient.doesObjectExist(OSSConfig.BUCKET_NAME, key);
            System.out.println("Does object " + OSSConfig.BUCKET_NAME + " exist? " + exists + "\n");
            OSSObject o = ossClient.getObject(OSSConfig.BUCKET_NAME, key);
            System.out.println(o.getKey());
            System.out.println(o.getBucketName());
            System.out.println(o.getRequestId());
            

            ossClient.setObjectAcl(OSSConfig.BUCKET_NAME, key, CannedAccessControlList.PublicRead);
            ossClient.setObjectAcl(OSSConfig.BUCKET_NAME, key, CannedAccessControlList.Default);

            ObjectAcl objectAcl = ossClient.getObjectAcl(OSSConfig.BUCKET_NAME, key);
            System.out.println("ACL:" + objectAcl.getPermission().toString());

            /*
             * Download an object from your bucket
             */
            System.out.println("Downloading an object");
            OSSObject object = ossClient.getObject(OSSConfig.BUCKET_NAME, key);
            System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
            displayTextInputStream(object.getObjectContent());

            /*
             * List objects in your bucket by prefix
             */
            System.out.println("Listing objects");
            ObjectListing objectListing = ossClient.listObjects(OSSConfig.BUCKET_NAME, "My");
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + "  " +
                        "(size = " + objectSummary.getSize() + ")");
            }
            System.out.println();

            /*
             * Delete an object
             */
            System.out.println("Deleting an object\n");
//            ossClient.deleteObject(OSSConfig.BUCKET_NAME, key);

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
            ossClient.shutdown();
        }
    }

    private static File createSampleFile() throws IOException {
//        File file = File.createTempFile("oss-java-sdk-", ".txt");
//        file.deleteOnExit();

//        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
//        writer.write("abcdefghijklmnopqrstuvwxyz\n");
//        writer.write("0123456789011234567890\n");
//        writer.close();
    	File file = new File("/Users/shisfish/Desktop/cc.jpg");

        return file;
    }

    private static void displayTextInputStream(InputStream input) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }

            System.out.println("    " + line);
        }
        System.out.println();

        reader.close();
    }



}
